﻿using BlogApi.Data;
using BlogApi.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogApi.Services
{
    public class ArticleTagRepository:IArticleTagRepository
    {
        private readonly BlogDbContext _context;

        public ArticleTagRepository(BlogDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }
        public async Task<IEnumerable<ArticleTag>> GetArticleTagsAsync()
        {
            return await _context.ArticleTags_table.ToListAsync();
        }
        public async Task<IEnumerable<ArticleTag>> GetArticleTagsByPageAsync(int pageSize, int pageIndex)
        {
            return await _context.ArticleTags_table.Skip(pageSize * pageIndex).Take(pageSize).ToListAsync();
        }
        public async Task<IEnumerable<ArticleTag>> GetUserArticleTagsByPageAsync(Guid userId, int pageSize, int pageIndex)
        {
            return await _context.ArticleTags_table.Where(t => t.UserId == userId).Skip(pageSize * pageIndex).Take(pageSize).ToListAsync();
        }
        public async Task<ArticleTag> GetArticleTagAsync(Guid articleTagId)
        {
            if (articleTagId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(articleTagId));
            }
            return await _context.ArticleTags_table.FirstOrDefaultAsync(item => item.Id == articleTagId);
        }
        public void AddArticleTag(ArticleTag articleTag)
        {
            if (articleTag == null)
            {
                throw new ArgumentNullException(nameof(articleTag));
            }
            _context.ArticleTags_table.Add(articleTag);
        }
        public void UpdateArticleTag(ArticleTag articleTag)
        {
            //由于数据库上下文会对实体进行跟踪 所以这句话可以不写
            //_context.Entry(articleTag).State = EntityState.Modified;
        }
        public void DeleteArticleTag(ArticleTag articleTag)
        {
            if (articleTag == null)
            {
                throw new ArgumentNullException(nameof(articleTag));
            }
            _context.ArticleTags_table.Remove(articleTag);
        }
        public async Task<bool> ArticleTagExistsAsync(Guid articleTagId)
        {
            if (articleTagId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(articleTagId));
            }
            return await _context.ArticleTags_table.AnyAsync(tag => tag.Id == articleTagId);
        }
        public async Task<bool> UserArticleTagNameExistsAsync(string articleTagName, Guid userId)
        {
            return await _context.ArticleTags_table.AnyAsync(tag => tag.TagName == articleTagName && tag.UserId == userId);
        }
        public async Task<bool> SaveAsync()
        {
            return await _context.SaveChangesAsync() >= 0;
        }
    }
}
